@model CaipuGuanliXitong.Models.RecipeIngredientDto

@{
    ViewData["Title"] = "新增带量食材（批量）";
}

<h2>新增带量食材（批量）</h2>

<h4>为一个菜谱添加多个食材</h4>
<hr />
<div class="row">
    <div class="col-md-8">
        <form asp-action="CreateMultiple" id="createMultipleForm">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            
            <div class="form-group">
                <label class="control-label">选择菜谱</label>
                <div class="input-group">
                    <input type="text" id="cookBookAutoComplete" class="form-control" placeholder="输入菜谱名称进行搜索">
                    <input type="hidden" asp-for="CookBookId" id="CookBookId" />
                    <input type="hidden" asp-for="CookBookName" id="CookBookName" />
                </div>
                <span asp-validation-for="CookBookId" class="text-danger"></span>
                <small class="form-text text-muted">输入菜谱名称，系统将自动搜索匹配的菜谱</small>
            </div>
            
            <hr />
            
            <h5>食材列表</h5>
            <div class="form-group">
                <button type="button" class="btn btn-info" onclick="addIngredientRow()">
                    <i class="fas fa-plus"></i> 添加食材
                </button>
            </div>
            
            <div class="form-group">
                <table class="table table-bordered" id="ingredientsTable">
                    <thead>
                        <tr>
                            <th>食材</th>
                            <th style="width: 150px;">用量</th>
                            <th style="width: 100px;">操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- 动态添加的食材行将在这里显示 -->
                    </tbody>
                </table>
                <span class="text-danger" id="ingredientsValidation"></span>
            </div>
            
            <div class="form-group">
                <input type="submit" value="创建" class="btn btn-primary" />
                <a asp-action="Index" class="btn btn-secondary">返回列表</a>
            </div>
        </form>
    </div>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    
    <style>
        .autocomplete-items {
            position: absolute;
            border: 1px solid #d4d4d4;
            border-bottom: none;
            border-top: none;
            z-index: 99;
            top: 100%;
            left: 0;
            right: 0;
        }

        .autocomplete-items div {
            padding: 10px;
            cursor: pointer;
            background-color: #fff;
            border-bottom: 1px solid #d4d4d4;
        }

        .autocomplete-items div:hover {
            background-color: #e9e9e9;
        }

        .autocomplete-active {
            background-color: DodgerBlue !important;
            color: #ffffff;
        }
    </style>
    
    <script>
        $(document).ready(function () {
            // 初始化菜谱自动完成搜索
            initCookBookAutoComplete();
            
            // 表单提交验证
            $('#createMultipleForm').submit(function(e) {
                var cookBookId = $('#CookBookId').val();
                var ingredientCount = $('#ingredientsTable tbody tr').length;
                
                if (!cookBookId) {
                    e.preventDefault();
                    alert('请选择一个菜谱');
                    return false;
                }
                
                if (ingredientCount === 0) {
                    e.preventDefault();
                    $('#ingredientsValidation').text('请至少添加一个食材');
                    return false;
                }
                
                // 检查是否有空的食材或用量
                var hasEmpty = false;
                $('#ingredientsTable tbody tr').each(function() {
                    var ingredientId = $(this).find('input.ingredient-id').val();
                    var quantity = $(this).find('input.quantity-input').val();
                    
                    if (!ingredientId || !quantity || quantity <= 0) {
                        hasEmpty = true;
                        return false;
                    }
                });
                
                if (hasEmpty) {
                    e.preventDefault();
                    $('#ingredientsValidation').text('请确保所有食材都已选择且用量大于0');
                    return false;
                }
                
                $('#ingredientsValidation').text('');
            });
        });
        
        function initCookBookAutoComplete() {
            var input = document.getElementById("cookBookAutoComplete");
            var currentFocus;
            
            input.addEventListener("input", function(e) {
                var val = this.value;
                closeAllLists();
                if (!val) { return false; }
                currentFocus = -1;
                
                // 创建包含搜索结果的DIV元素
                var autocompleteList = document.createElement("DIV");
                autocompleteList.setAttribute("id", this.id + "autocomplete-list");
                autocompleteList.setAttribute("class", "autocomplete-items");
                this.parentNode.appendChild(autocompleteList);
                
                // 发送AJAX请求获取搜索结果
                $.ajax({
                    url: '@Url.Action("SearchCookBooks", "RecipeIngredient")',
                    type: 'GET',
                    data: { term: val },
                    success: function(data) {
                        // 清空现有列表
                        autocompleteList.innerHTML = '';
                        
                        if (data.length > 0) {
                            // 为每个搜索结果创建DIV元素
                            data.forEach(function(item) {
                                var itemDiv = document.createElement("DIV");
                                itemDiv.innerHTML = "<strong>" + item.text.substr(0, val.length) + "</strong>";
                                itemDiv.innerHTML += item.text.substr(val.length);
                                itemDiv.innerHTML += "<input type='hidden' value='" + item.text + "' data-id='" + item.id + "'>";
                                itemDiv.addEventListener("click", function(e) {
                                    // 当点击某个选项时，填充输入框和隐藏字段
                                    input.value = this.getElementsByTagName("input")[0].value;
                                    document.getElementById("CookBookId").value = this.getElementsByTagName("input")[0].getAttribute('data-id');
                                    document.getElementById("CookBookName").value = this.getElementsByTagName("input")[0].value;
                                    closeAllLists();
                                });
                                autocompleteList.appendChild(itemDiv);
                            });
                        } else {
                            // 没有找到匹配项时显示提示
                            var itemDiv = document.createElement("DIV");
                            itemDiv.innerHTML = "未找到匹配的菜谱";
                            itemDiv.classList.add("disabled");
                            autocompleteList.appendChild(itemDiv);
                        }
                    },
                    error: function() {
                        // 出错时显示提示
                        var autocompleteList = document.getElementById(input.id + "autocomplete-list");
                        if (autocompleteList) {
                            autocompleteList.innerHTML = '';
                            var itemDiv = document.createElement("DIV");
                            itemDiv.innerHTML = "搜索出错，请重试";
                            itemDiv.classList.add("disabled");
                            autocompleteList.appendChild(itemDiv);
                        }
                    }
                });
            });
            
            // 处理键盘导航
            input.addEventListener("keydown", function(e) {
                var autocompleteList = document.getElementById(this.id + "autocomplete-list");
                if (autocompleteList) var items = autocompleteList.getElementsByTagName("div");
                if (e.keyCode == 40) {
                    // 向下键
                    currentFocus++;
                    addActive(items);
                } else if (e.keyCode == 38) {
                    // 向上键
                    currentFocus--;
                    addActive(items);
                } else if (e.keyCode == 13) {
                    // 回车键
                    e.preventDefault();
                    if (currentFocus > -1 && items) {
                        items[currentFocus].click();
                    }
                }
            });
            
            function addActive(items) {
                if (!items) return false;
                removeActive(items);
                if (currentFocus >= items.length) currentFocus = 0;
                if (currentFocus < 0) currentFocus = (items.length - 1);
                items[currentFocus].classList.add("autocomplete-active");
            }
            
            function removeActive(items) {
                for (var i = 0; i < items.length; i++) {
                    items[i].classList.remove("autocomplete-active");
                }
            }
            
            function closeAllLists(elmnt) {
                var autocompleteLists = document.getElementsByClassName("autocomplete-items");
                for (var i = 0; i < autocompleteLists.length; i++) {
                    if (elmnt != autocompleteLists[i] && elmnt != input) {
                        autocompleteLists[i].parentNode.removeChild(autocompleteLists[i]);
                    }
                }
            }
            
            // 点击页面其他地方时关闭搜索列表
            document.addEventListener("click", function (e) {
                closeAllLists(e.target);
            });
        }
        
        function initIngredientAutoComplete(inputElement) {
            var currentFocus;
            
            inputElement.addEventListener("input", function(e) {
                var val = this.value;
                closeAllIngredientLists();
                if (!val) { return false; }
                currentFocus = -1;
                
                // 创建包含搜索结果的DIV元素
                var autocompleteList = document.createElement("DIV");
                autocompleteList.setAttribute("id", this.id + "autocomplete-list");
                autocompleteList.setAttribute("class", "autocomplete-items");
                this.parentNode.appendChild(autocompleteList);
                
                // 发送AJAX请求获取搜索结果
                $.ajax({
                    url: '@Url.Action("SearchIngredients", "RecipeIngredient")',
                    type: 'GET',
                    data: { term: val },
                    success: function(data) {
                        // 清空现有列表
                        autocompleteList.innerHTML = '';
                        
                        if (data.length > 0) {
                            // 为每个搜索结果创建DIV元素
                            data.forEach(function(item) {
                                var itemDiv = document.createElement("DIV");
                                itemDiv.innerHTML = "<strong>" + item.text.substr(0, val.length) + "</strong>";
                                itemDiv.innerHTML += item.text.substr(val.length);
                                itemDiv.innerHTML += "<input type='hidden' value='" + item.text + "' data-id='" + item.id + "'>";
                                itemDiv.addEventListener("click", function(e) {
                                    // 当点击某个选项时，填充输入框和隐藏字段
                                    inputElement.value = this.getElementsByTagName("input")[0].value;
                                    inputElement.parentNode.querySelector('.ingredient-id').value = this.getElementsByTagName("input")[0].getAttribute('data-id');
                                    closeAllIngredientLists();
                                });
                                autocompleteList.appendChild(itemDiv);
                            });
                        } else {
                            // 没有找到匹配项时显示提示
                            var itemDiv = document.createElement("DIV");
                            itemDiv.innerHTML = "未找到匹配的食材";
                            itemDiv.classList.add("disabled");
                            autocompleteList.appendChild(itemDiv);
                        }
                    },
                    error: function() {
                        // 出错时显示提示
                        var autocompleteList = document.getElementById(inputElement.id + "autocomplete-list");
                        if (autocompleteList) {
                            autocompleteList.innerHTML = '';
                            var itemDiv = document.createElement("DIV");
                            itemDiv.innerHTML = "搜索出错，请重试";
                            itemDiv.classList.add("disabled");
                            autocompleteList.appendChild(itemDiv);
                        }
                    }
                });
            });
            
            // 处理键盘导航
            inputElement.addEventListener("keydown", function(e) {
                var autocompleteList = document.getElementById(this.id + "autocomplete-list");
                if (autocompleteList) var items = autocompleteList.getElementsByTagName("div");
                if (e.keyCode == 40) {
                    // 向下键
                    currentFocus++;
                    addActive(items);
                } else if (e.keyCode == 38) {
                    // 向上键
                    currentFocus--;
                    addActive(items);
                } else if (e.keyCode == 13) {
                    // 回车键
                    e.preventDefault();
                    if (currentFocus > -1 && items) {
                        items[currentFocus].click();
                    }
                }
            });
            
            function addActive(items) {
                if (!items) return false;
                removeActive(items);
                if (currentFocus >= items.length) currentFocus = 0;
                if (currentFocus < 0) currentFocus = (items.length - 1);
                items[currentFocus].classList.add("autocomplete-active");
            }
            
            function removeActive(items) {
                for (var i = 0; i < items.length; i++) {
                    items[i].classList.remove("autocomplete-active");
                }
            }
        }
        
        function closeAllIngredientLists(elmnt) {
            var autocompleteLists = document.getElementsByClassName("autocomplete-items");
            for (var i = 0; i < autocompleteLists.length; i++) {
                if (elmnt != autocompleteLists[i]) {
                    autocompleteLists[i].parentNode.removeChild(autocompleteLists[i]);
                }
            }
        }
        
        function addIngredientRow() {
            var rowIndex = getRowCount();
            var rowHtml = '<tr>' +
                '<td>' +
                '<div class="input-group">' +
                '<input type="text" class="form-control ingredient-autocomplete" placeholder="输入食材名称进行搜索">' +
                '<input type="hidden" class="ingredient-id" name="Ingredients[' + rowIndex + '].IngredientId">' +
                '</div>' +
                '</td>' +
                '<td>' +
                '<input type="number" class="form-control quantity-input" name="Ingredients[' + rowIndex + '].Quantity" step="0.001" min="0.001" placeholder="用量">' +
                '</td>' +
                '<td>' +
                '<button type="button" class="btn btn-danger btn-sm" onclick="removeIngredientRow(this)">' +
                '<i class="fas fa-trash"></i> 删除</button>' +
                '</td>' +
                '</tr>';
            
            $('#ingredientsTable tbody').append(rowHtml);
            
            // 初始化新添加行的食材自动完成搜索
            var newInput = $('#ingredientsTable tbody tr:last .ingredient-autocomplete')[0];
            initIngredientAutoComplete(newInput);
        }
        
        function removeIngredientRow(button) {
            $(button).closest('tr').remove();
            // 重新编号
            renumberRows();
        }
        
        function getRowCount() {
            return $('#ingredientsTable tbody tr').length;
        }
        
        function renumberRows() {
            $('#ingredientsTable tbody tr').each(function(index) {
                $(this).find('.ingredient-id').attr('name', 'Ingredients[' + index + '].IngredientId');
                $(this).find('input.quantity-input').attr('name', 'Ingredients[' + index + '].Quantity');
            });
        }
        
        // 点击页面其他地方时关闭食材搜索列表
        document.addEventListener("click", function (e) {
            closeAllIngredientLists(e.target);
        });
    </script>
}